/**
 * @description 遥感组件
 * @date 2024.9.10
 * @author wz
 * @midify 2025.5.15
 * @editor wz
 */
import { _decorator, Component, EventTouch, Node, UITransform, v2, v3, Vec2 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('CJoystick')
export class CJoystick extends Component {
    @property(Node)
    joystickBg: Node;               //摇杆背景
    @property(Node)
    joystickHandle: Node;           //摇杆手柄
    @property(Number)
    maxDistance: number = 100;      //手柄的最大偏移距离

    private _isTouch: boolean = false;
    private _dir: Vec2 = v2();


    callback_touchMove: (direction: Vec2) => void = null;
    callback_touchEnd: () => void = null;
    onLoad() {
        this._isTouch = false;
        this.joystickBg.on(Node.EventType.TOUCH_START, this._onTouchStart, this);
        this.joystickBg.on(Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
        this.joystickBg.on(Node.EventType.TOUCH_END, this._onTouchEnd, this);
        this.joystickBg.on(Node.EventType.TOUCH_CANCEL, this._onTouchEnd, this);
    }


    private _freshMoveHandle(event: EventTouch) {
        let worldPos = this.joystickBg.getComponent(UITransform).convertToWorldSpaceAR(v3())
        let delta = event.getLocation().subtract(v2(worldPos.x, worldPos.y));
        let distance = delta.length();
        if (distance > this.maxDistance)
            delta = delta.normalize().multiplyScalar(this.maxDistance);
        this.joystickHandle.setPosition(delta.x, delta.y);
        this._dir = v2(delta.x / this.maxDistance, delta.y / this.maxDistance).normalize();

    }


    private _onTouchStart(event: EventTouch) {
        this._isTouch = true;
        this._freshMoveHandle(event);
    };

    private _onTouchMove(event: EventTouch) {
        if (!this._isTouch) return;
        this._freshMoveHandle(event);
    };

    private _onTouchEnd(event: EventTouch) {
        this._isTouch = false;
        this.joystickHandle.setPosition(v3());
        if (this.callback_touchEnd) this.callback_touchEnd()
    };

    protected update(dt: number): void {
        if (this._isTouch && this._dir.x && this._dir.y) {
            if (this.callback_touchMove) this.callback_touchMove(this._dir)
        }
    }
}


